package com.tutorialspoint;

import com.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.print.attribute.standard.DateTimeAtCompleted;
import javax.sql.DataSource;
import java.time.DateTimeException;
import java.util.List;

public class StudentJDBCTemplate implements StudentDao {

    private JdbcTemplate jdbcTemplate ;
    @Override
    public void setDataSource(DataSource ds) {
            this.jdbcTemplate = new JdbcTemplate(ds);
    }

    @Override
    public void create(String name, Integer age, Integer marks, Integer year) {
        try{
            String sql1 = "insert into Student (name,age) values(?,?)";
            jdbcTemplate.update(sql1,name,age);
            String sql2 = "select max(id) from Student";
            int sid = jdbcTemplate.queryForInt(sql2);
            String sql3 = "insert into Marks(sid,marks,year)"+"values(?,?,?)";
            jdbcTemplate.update(sql3,sid,marks,year);
            System.out.println("Created name="+name+"Age"+age);
          //  throw new RuntimeException("simulate Error condition");
        }catch (DataAccessException e){
           // System.out.println("Error in creating record,rolling back ");
          //  throw e;
        }

    }

    @Override
    public List<StudentMarks> listStudents() {
        String sql = "select * from Student,Marks where Student.id = Marks.sid";
        List<StudentMarks> studentMarks = jdbcTemplate.query(sql,new StudentMarksMapper());
        return studentMarks;
    }

}
